<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 标题 -->
      <template #header>
        <div class="title-content">发送模板消息</div>
      </template>
      <el-row :gutter="20" style="width: 100%">
        <el-col :span="24">
          <el-descriptions :column="1" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  {{ $t("task.procInstName") }}
                </div>
              </template>
              {{ route.query.procInstName as string }}
            </el-descriptions-item>
            <!-- 微信公众号 -->
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  {{ $t("user.authorizerAppid") }}
                </div>
              </template>
              {{
                Dict.authorizerAppidBizDict.getValue(
                  route.query.authorizerAppid as string,
                )
              }}
            </el-descriptions-item>
            <!-- 消息模板 -->
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  {{ $t("user.templateId") }}
                </div>
              </template>
              <jmash-select
                v-model="table.templateId"
                :placeholder="$t('user.templateIdRequired')"
                :data="templateIdBizDict.values"
                clearable
                @change="templateEvent"
              />
            </el-descriptions-item>
            <!-- 模板 -->
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  {{ $t("user.content") }}
                </div>
              </template>
              {{ table.content }}
            </el-descriptions-item>
            <!-- 示例 -->
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  {{ $t("user.example") }}
                </div>
              </template>
              <div style="white-space: pre" v-html="table.example"></div>
            </el-descriptions-item>
          </el-descriptions>
          <!-- 动态表格 -->
          <el-table
            style="width: 100%"
            border
            class="margin-top"
            :data="table.dataList"
          >
            <el-table-column
              prop="key"
              :label="$t('user.Key')"
              width=184
            />
            <el-table-column :label="$t('user.contents')" prop="content"  width:="70%">
              <template #default="scope">
                <el-input
                  v-model="scope.row.content"
                  :placeholder="$t('user.required')"
                   maxlength="20"
                   show-word-limit
                   clearable
                />
              </template>
            </el-table-column>
          </el-table>
          <!-- 查看详情url -->
          <el-col :span="24" class="margin-top">
            <el-form-item :label="$t('user.url')" prop="url">
              <el-input
                v-model="form.url"
                :placeholder="$t('user.urlRequired')"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
      <template #footer>
        <!-- 发送按钮 -->
        <el-button type="primary" @click="submitForm">
          {{ $t("user.send") }}
        </el-button>
        <!-- 返回按钮 -->
        <el-button type="primary" @click="routerBack">
          {{ $t("common.back") }}
        </el-button>
      </template>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { onBeforeMount, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { routerUtil, vueMetaEnv } from "jmash-core";
import { userApi, type UserOpenModel } from "jmash-rbac";
import {
  TemplateIdBizDict,
  type MsgTemplateModel,
  msgTemplateApi,
  type dataListModel,
  type UserModel,
  wxUserApi
} from "xyvcard-wechat";
const router = useRouter();
const route = useRoute();
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { Dict } from "@/api/flow/dict";

let form: UserModel = reactive<UserModel>({});
let table: MsgTemplateModel = reactive<MsgTemplateModel>({});
const userData = ref<UserOpenModel[]>([]);

// 消息模板
const templateIdBizDict = ref();
templateIdBizDict.value = new TemplateIdBizDict({
  authorizerAppid: route.query.authorizerAppid,
});
templateIdBizDict.value.useValues();
Dict.authorizerAppidBizDict.useValues();
// 获取模板数据
function templateEvent(templateId: string) {
  msgTemplateApi.findById({ templateId: templateId }).then(({ data }) => {
    data.dataList = data.dataList?.map((item) => {
      return {
        key: item,
        content: "",
      };
    }) as Array<dataListModel>;
    Object.assign(table, data);
  });
}

//返回
function routerBack() {
  routerUtil.closeTagView(route.fullPath, router, false);
}

// 表格数据
onBeforeMount(() => {
  userApi
    .openList({
      userId: route.query.userId as string,
      tenant: vueMetaEnv.APP_TENANT,
    })
    .then(({ data }) => {
      userData.value = data.results;
      console.log("userData", userData.value);
    });
});
function convertDataListToMap(dataList: Array<dataListModel>) {
  const json: Record<string, string> = {};
  for (let i = 0; i < dataList.length; i++) {
    const item = dataList[i];
    json[item.key] =item.content;
  }
  return json;
}
// 发送模板消息
const submitForm = async () => {
  const json: Record<string, string>= convertDataListToMap(table.dataList as Array<dataListModel>);
    wxUserApi
    .send({
      authorizerAppid: route.query.authorizerAppid as string,
      data:json,
      templateCode: table.templateCode,
      url: form.url,
      toUnionId: userData.value[0].unionId,
    })
    .then(({ status }) => {
      if (status === 200) {
        ElMessage({
          message: t("user.sendSuccess"),
          type: "success",
        });
        routerUtil.closeTagView(route.fullPath, router, false);
      } else {
        ElMessage({
          message: t("user.sendFail"),
          type: "error",
        });
      }
    });
};
</script>
<style scoped lang="scss">
.margin-top {
  margin-top: 20px;
}
</style>
